package com.bayihouse.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bayihouse.annotation.AuthCheck;
import com.bayihouse.common.BaseResponse;
import com.bayihouse.common.DeleteRequest;
import com.bayihouse.common.ErrorCode;
import com.bayihouse.common.ResultUtils;
import com.bayihouse.constant.AdministerConstant;
import com.bayihouse.exception.BusinessException;
import com.bayihouse.exception.ThrowUtils;
import com.bayihouse.model.entity.*;
import com.bayihouse.model.request.room.RoomAddRequest;
import com.bayihouse.model.request.room.RoomQueryRequest;
import com.bayihouse.model.request.room.RoomUpdateRequest;
import com.bayihouse.model.vo.RoomDetailVO;
import com.bayihouse.model.vo.RoomVO;
import com.bayihouse.service.*;
import com.bayihouse.utils.MyObjectUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/room")
@Slf4j
public class RoomController {

    @Resource
    private RoomService roomService;

    @Resource
    private UnitService unitService;

    @Resource
    private CommunityService communityService;
    @Resource
    private HouseService houseService;
    @Resource
    private NetObjectService netObjectService;

    @Resource
    private OccupantService occupantService;


    private final Gson GSON = new Gson();


    // endregion

    // region 增删改查

    /**
     * 创建用户
     *
     * @param roomAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Long> addRoom(@RequestBody RoomAddRequest roomAddRequest, HttpServletRequest request) {
        if (roomAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Room room = new Room();
        List<String> label = roomAddRequest.getLabel();
        if (label != null) {
            room.setLabel(GSON.toJson(label));
        }
        BeanUtils.copyProperties(roomAddRequest, room);
        boolean result = roomService.save(room);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(room.getId());
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> deleteRoom(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = roomService.removeById(deleteRequest.getId());
        return ResultUtils.success(b);
    }

    /**
     * 更新用户
     *
     * @param roomUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Boolean> updateRoom(@RequestBody RoomUpdateRequest roomUpdateRequest,
                                            HttpServletRequest request) {
        System.out.println(roomUpdateRequest);
        if (roomUpdateRequest == null || roomUpdateRequest.getId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Room room = new Room();
        List<String> label = roomUpdateRequest.getLabel();
        if (label != null) {
            room.setLabel(GSON.toJson(label));
        }
        BeanUtils.copyProperties(roomUpdateRequest, room);
        boolean result = roomService.updateById(room);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * @param id
     * @param request
     * @return
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<RoomDetailVO> getRoomVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        RoomDetailVO roomDetailVO = new RoomDetailVO();
        Room room = roomService.getById(id);
        BeanUtils.copyProperties(room, roomDetailVO);
        roomDetailVO = RoomDetailVO.objToVO(room);
        String label = room.getLabel();
        Date createTime = room.getCreateTime();
        Date updateTime = room.getUpdateTime();
        Long householdId = room.getHouseholdId();
        if (householdId != null) {
            Occupant occupant = occupantService.getById(householdId);
            roomDetailVO.setHousehold(occupant.getName());
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String createTimeStr = simpleDateFormat.format(createTime);
        String updateTimeStr = simpleDateFormat.format(updateTime);
        roomDetailVO.setCreateTime(createTimeStr);
        roomDetailVO.setUpdateTime(updateTimeStr);

        String labelStr = "";
        List<String> list = GSON.fromJson(label, new TypeToken<List<String>>() {
        }.getType());
        if (!MyObjectUtils.isArraysEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (i != 0) {
                    labelStr += ",";
                }
                labelStr += list.get(i);
            }
        }
        roomDetailVO.setLabel(labelStr);
        ThrowUtils.throwIf(room == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(roomDetailVO);
    }

    @PostMapping("/getById")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Room> getRoomById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Room room = roomService.getById(id);
        ThrowUtils.throwIf(room == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(room);
    }


    /**
     * 分页获取用户列表（仅管理员）
     *
     * @param roomQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Page<Room>> listRoomByPage(@RequestBody RoomQueryRequest roomQueryRequest,
                                                   HttpServletRequest request) {
        long current = roomQueryRequest.getCurrent();
        long size = roomQueryRequest.getPageSize();
        Page<Room> roomPage = roomService.page(new Page<>(current, size),
                roomService.getQueryWrapper(roomQueryRequest));
        return ResultUtils.success(roomPage);
    }

    /**
     * 分页获取用户封装列表
     *
     * @param roomQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    @AuthCheck(mustRole = AdministerConstant.DEFAULT_ROLE)
    public BaseResponse<Page<RoomVO>> listRoomVOByPage(@RequestBody RoomQueryRequest roomQueryRequest,
                                                       HttpServletRequest request) {
        if (roomQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = roomQueryRequest.getCurrent();
        long size = roomQueryRequest.getPageSize();
        QueryWrapper<Room> queryWrapper = null;
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        if (roomQueryRequest.getUnitId() == null) {
            queryWrapper = roomService.getQueryWrapper(roomQueryRequest);
        } else {
            if (roomQueryRequest.getUnitId() == -1) {
                roomQueryRequest.setUnitId(null);
                queryWrapper = roomService.getQueryWrapper(roomQueryRequest);
                queryWrapper.isNull("unitId");
            } else {
                queryWrapper = roomService.getQueryWrapper(roomQueryRequest);
            }
        }

        Page<Room> roomPage = roomService.page(new Page<>(current, size), queryWrapper
        );
        System.out.println(roomPage.getRecords());
        Page<RoomVO> roomVOPage = new Page<>(current, size, roomPage.getTotal());
        List<RoomVO> roomVO = roomService.getRoomVOList(roomPage.getRecords());
        roomVOPage.setRecords(roomVO);
        System.out.println(roomVOPage.getRecords());
        return ResultUtils.success(roomVOPage);
    }

}

